<template>
  <div class="about-page">
      <h1>饮食记录</h1>
      
      <!-- 添加记录表单 -->
      <div class="add-record-form">
          <h3>添加饮食记录</h3>
          <div class="form-group">
              <label>食物:</label>
              <select v-model.number="newRecord.food_id">
                  <option v-for="food in foods" :value="food.food_id" :key="food.food_id">{{ food.name }}</option>
              </select>
          </div>
          <div class="form-group">
              <label>数量:</label>
              <input v-model.number="newRecord.quantity" type="number" placeholder="数量" />
          </div>
          <button @click="addRecord">添加记录</button>
      </div>
      
      <!-- 饮食记录表格 -->
      <table>
          <thead>
              <tr>
                  <th>food（食物）</th>
                  <th>quantity（数量）</th>
                  <th>record_time（记录时间）</th>
                  <th>操作</th>
              </tr>
          </thead>
          <tbody>
              <tr v-for="(record, index) in dietRecords" :key="record.record_id">
                  <td>{{ record.food_name }}</td>
                  <td>{{ record.quantity }}</td>
                  <td>{{ formatDate(record.record_time) }}</td>
                  <td>
                      <button @click="deleteRecord(record.record_id)">删除</button>
                  </td>
              </tr>
          </tbody>
      </table>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/stores/counter'; // 引入用户store

const userStore = useUserStore(); // 创建用户store实例
const dietRecords = ref([]);
const newRecord = ref({
  user_id: null, // 通过计算属性动态获取
  food_id: 1,
  quantity: 100,
  record_time: new Date().getTime()
});
const foods = ref([]);

// 时间戳格式化函数
const formatDate = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleString();
};

// 获取食物列表
const fetchFoods = async () => {
  try {
      const response = await axios.get('http://localhost:8080/MDMS0214_war/food/all');
      foods.value = response.data;
  } catch (error) {
      console.error('获取食物列表失败:', error);
  }
};

// 获取饮食记录（修改接口路径）
const fetchDietRecords = async () => {
  try {
      const response = await axios.get('http://localhost:8080/MDMS0214_war/diet_record/all/with_food');
      
      // 过滤当前用户的记录
      dietRecords.value = response.data.filter(record => record.user_id === userStore.userId);
  } catch (error) {
      console.error('获取饮食记录失败:', error);
  }
};

// 添加饮食记录（修改接口路径）
const addRecord = async () => {
  try {
      newRecord.value.record_time = new Date().getTime();
      newRecord.value.user_id = userStore.userId; // 从store获取用户ID
      
      const response = await axios.post(
          'http://localhost:8080/MDMS0214_war/diet_record/add',
          newRecord.value
      );
      
      if (response.data > 0) {
          alert('添加成功');
          fetchDietRecords();
          newRecord.value = {
              user_id: userStore.userId, // 重置表单时保持用户ID
              food_id: 1,
              quantity: 100,
              record_time: new Date().getTime()
          };
      } else {
          alert('添加失败');
      }
  } catch (error) {
      console.error('添加记录失败:', error);
      alert('添加失败：' + error.message);
  }
};

// 删除饮食记录（修改接口路径）
const deleteRecord = async (recordId) => {
  if (confirm('确定要删除这条记录吗？')) {
      try {
          const response = await axios.delete(
              `http://localhost:8080/MDMS0214_war/diet_record/${recordId}`
          );
          
          if (response.data > 0) {
              alert('删除成功');
              fetchDietRecords();
          } else {
              alert('删除失败');
          }
      } catch (error) {
          console.error('删除记录失败:', error);
          alert('删除失败：' + error.message);
      }
  }
};

onMounted(() => {
  fetchFoods();
  fetchDietRecords();
});
</script>

<style scoped>
/* 样式保持不变 */
.about-page {
  font-family: Arial, sans-serif;
  padding: 20px;
}

.add-record-form {
  margin-bottom: 20px;
  padding: 15px;
  background-color: rgba(240, 240, 240, 0.8);
  border-radius: 5px;
}

.form-group {
  margin-bottom: 10px;
}

.form-group label {
  display: inline-block;
  width: 80px;
}

.form-group input, .form-group select {
  padding: 5px;
  width: 200px;
}

button {
  padding: 8px 15px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
}

button:hover {
  background-color: #45a049;
}

table {
  border-collapse: collapse;
  width: 100%;
  background-color: rgba(255, 255, 255, 0.8);
}

th, td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}

h1 {
  text-shadow: 0 0 5px white;
}
</style>